package com.android.cl.coludtf.network;

import com.android.cl.coludtf.model.Result;
import com.android.cl.coludtf.utils.Urls;
import com.android.cl.coludtf.utils.log.MyLog;
import com.google.gson.Gson;

import org.apache.commons.io.IOUtils;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cz.msebera.android.httpclient.protocol.HTTP;

public class HttpHelper {
    private static String TAG = "HttperHelper";
    private Gson gson = new Gson();
    private Result result = new Result();

    public Result post(String getUrl, String token, String requestJson) throws IOException {

        URL url = new URL(getUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            //设置请求头
            connection.setRequestProperty(Urls.AUTH, token);
            connection.setRequestProperty(HTTP.CONTENT_TYPE, Urls.JSON_TYPE);
            //请求参数设定
            connection.setConnectTimeout(Urls.HTTP_TIME_OUT);
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.connect();
            // POST请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(requestJson);
            out.flush();
            out.close();
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                //将流转换为字符串。
                String re = IOUtils.toString(inputStream, "utf-8");
                MyLog.i(TAG, re);
                result = gson.fromJson(re, Result.class);
            } else {
                result.setCode(responseCode + "");
                result.setMessage("网络请求失败！");
            }
        } catch (Exception e) {
            MyLog.i(TAG, e.getMessage());
            e.printStackTrace();
        } finally {
            // 断开连接
            connection.disconnect();
        }
        return result;
    }
}
